debug("Ready now.\n**********************************");
var Config = {
    portSocket: 10000,//如果客户端不直连端口，可能需要前端上nginx做一下反向代理
    secret:"",
};
var blackLoginList = [];
var blackChatList = [];
var masterList = ['145025'];//这里根据id做一个简单的管理员列表
var websocket = require("nodejs-websocket"),
crypto = require('crypto'),
http = require('http');
var webSocketServer = websocket.createServer(function(conn) {
    var query = login(conn.path);
    if (!query) {
        debug("客户端连接失败(登录失败)");
        conn.close();
    }else{
        debug("客户端连接成功 "+query.account);
    }
    if(blackLoginList.indexOf(query.account+"")!=-1){
        //禁止登录帐号
        debug("客户端连接失败(禁止登录)");
        conn.close();
    }
    conn.on("close",
    function(code, reason) {
        debug("客户端连接失败(用户断开)");
    });
    conn.on("error",
    function(code, reason) {
        debug("客户端连接失败(用户断开)");
    });
    conn.on("text",
    function(msg) {
        if(blackLoginList.indexOf(query.account+"")!=-1){
            //禁止登录帐号
            debug("客户端连接失败(禁止登录)");
            conn.close();
        }
        if(blackChatList.indexOf(query.account+"")!=-1){
            //禁止发言帐号
            debug("帐号被禁止发言("+query.account+")");
            return;
        }
        if(msg=="heartBeat"){
            debug("heartBeat");
            return;
        }
        try {
            var msgObj = JSON.parse(msg);
            switch (msgObj.type) {
            case 'system':
                webSocketServer.connections.forEach(function(conn) {
                    conn.sendText(msgObj.msg);
                });
                break;
            case 'channel':
                if(masterList.indexOf(query.account+"")!=-1){
                    var _obj = JSON.parse(decodeURIComponent(msgObj.msg));
                    switch(_obj.msgType){
                        case 'login_set':
                            if(blackLoginList.indexOf(_obj.account+"")==-1){
                                blackLoginList.push(_obj.account+"");
                            }
                            _obj.msgType = 'system';
                            _obj.content = '用户 '+_obj.name+' 被管理员禁止登录!';
                            break;
                        case 'chat_set':
                            if(blackChatList.indexOf(_obj.account+"")==-1){
                                blackChatList.push(_obj.account+"");
                            }
                            _obj.msgType = 'system';
                            _obj.content = '用户 '+_obj.name+' 被管理员禁止发言!';
                            break;
                        case 'login_delete':
                            if(blackLoginList.indexOf(_obj.account+"")!=-1){
                                blackLoginList.splice(blackLoginList.indexOf(_obj.account+""),1);
                            }
                            _obj.msgType = 'system';
                            _obj.content = '用户 '+_obj.name+' 被管理员允许登录!';
                            break;
                        case 'chat_delete':
                            if(blackChatList.indexOf(_obj.account+"")!=-1){
                                blackChatList.splice(blackChatList.indexOf(_obj.account+""),1);
                            }
                            _obj.msgType = 'system';
                            _obj.content = '用户 '+_obj.name+' 被管理员允许发言!';
                            break;
                        case 'delete_all':
                            blackChatList = [];
                            blackLoginList = [];
                            _obj.msgType = 'system';
                            break;
                        default:
                            if(_obj.content.indexOf("@all")!=-1){
                                _obj.content=_obj.content.replace('@all','');
                                _obj.msgType='system';
                            }
                    }
                    msgObj.msg = encodeURIComponent(JSON.stringify(_obj));
                }
                webSocketServer.connections.forEach(function(conn) {
                    var query = new QueryString(conn.path);
                    if (query.channel == msgObj.to) {
                        conn.sendText(msgObj.msg);
                    }
                });
                break;
            case 'chat':
                webSocketServer.connections.forEach(function(conn) {
                    var query = new QueryString(conn.path);
                    if (query.account == msgObj.to) {
                        conn.sendText(msgObj.msg);
                    }
                });
                break;
            default:
                debug("不支持的消息类型：" + msgObj.type);
            }
        } catch(e) {
            console.log(e)
            debug("消息类型解析失败");
        }
    });
});
webSocketServer.listen(Config.portSocket);
debug("服务启动成功(" + Config.portSocket.toString() + ")Websocket");
checkConnection();
function checkConnection() {
    setTimeout(function() {
        debug("当前在线连接数：(" + webSocketServer.connections.length + ")");
        checkConnection();
    },
    10000);
}

function getTime() {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    if (hours < 10) {
        hours = "0" + hours;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    return hours + ":" + minutes + ":" + seconds;
}

function debug(message) {
    console.log(getTime()+" : "+message);
}

function login(url) {
    var query = new QueryString(url);
    if (sha1("account" + query.account + "channel" + query.channel+ Config.secret) == query.ticket) {
        return query;
    } else {
        return false;
    }
}

function QueryString(url) {
    var name, value;
    url = url.replace("/?", "");
    var arr = url.split("&"); //各个参数放到数组里
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = arr[i].substr(num + 1);
            this[name] = value;
        }
    }
}

function getTimeStamp(){
    return Date.parse(new Date())/1000;
}

function sha1(str) {
    var sha1 = crypto.createHash("sha1"); //定义加密方式:md5不可逆,此处的md5可以换成任意hash加密的方法名称；
    sha1.update(str);
    var res = sha1.digest("hex"); //加密后的值d
    return res;
}
